package com.rpcfx.client;


import com.alibaba.fastjson.parser.ParserConfig;
import com.rpcfx.DefaultRegistryCenterServiceImpl;
import com.rpcfx.api.LoadBalancer;
import com.rpcfx.api.RegistryCenterService;
import com.rpcfx.api.Router;
import com.rpcfx.api.RpcfxException;
import com.rpcfx.api.ServiceLoader;
import com.rpcfx.server.ObjectFactory;

import java.util.List;
import java.util.Map;

public final class Rpcfx {

    private static final Router router;

    private static final LoadBalancer loadBalancer;


    private static RegistryCenterService registryCenterService;


    public static int port = 20881;

    public static String connectingStr = "127.0.0.1:2181";

    static {
        ParserConfig.getGlobalInstance().addAccept("io.kimmking");
        List<Router> routerList = ServiceLoader.load(Router.class);
        router = routerList.get(0);

        List<LoadBalancer> loadBalancers = ServiceLoader.load(LoadBalancer.class);
        loadBalancer = loadBalancers.get(0);
        registryCenterService = new DefaultRegistryCenterServiceImpl(connectingStr, port);
    }

    public static <T> T create(final Class<T> serviceClass) {
        try {
            return ObjectFactory.getProxy(serviceClass, getUrl(serviceClass));
        } catch (RpcfxException e) {
            throw e;
        } catch (Exception e) {
            throw new RpcfxException(-1, e.getMessage());
        }
    }

    private static String getUrl(Class<?> serviceClass) {
        // 1. 简单：从zk拿到服务提供的列表
        // 2. 挑战：监听zk的临时节点，根据事件更新这个list（注意，需要做个全局map保持每个服务的提供者List）
        Map<String, List<String>> allServiceProvider = registryCenterService.getAllServiceProvider();
        List<String> invokers = allServiceProvider.get(serviceClass.getName());
        List<String> urls = router.route(invokers);
        return loadBalancer.select(urls); // router, loadbalance
    }

}
